//
//  SEGAdressListViewController.m
//  ExcellentHome
//
//  Created by 刘山 on 16/11/19.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGAdressListViewController.h"
#import "SEGEditAdressViewController.h"

#import "SEGEditAdressViewCell.h"
#import "SEGPersonalConfirmAlertView.h"



#import "SEGAdressListViewModel.h"

static NSString* SEGEditAdressViewCellIndentifier = @"_SEGEditAdressViewCellIndentifier";

@interface SEGAdressListViewController () <UITableViewDelegate,UITableViewDataSource,SEGEditAdressViewCellDelegate, SEGEditAdressViewControllerDelegate>

@property (nonatomic, strong) NSIndexPath *indexPath;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *bottomBtn;

/// viewModel
@property (nonatomic, strong) SEGAdressListViewModel *viewModel;

@end

@implementation SEGAdressListViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self seg_loadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"配送地址";
    self.view.backgroundColor = kColor_bg;

    [self setupUI];
    if (self.channel) self.viewModel.channel = self.channel;
}

#pragma mark - Load Data
- (void)seg_loadData {
    @weakify(self);
    [SVProgressHUD show];
    [self.viewModel.signal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SVProgressHUD dismiss];
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [self.tableView reloadData];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[SEGEditAdressViewCell class] forCellReuseIdentifier:SEGEditAdressViewCellIndentifier];
    self.tableView.backgroundColor = kColor_bg;
    [self.tableView setFrame:CGRectMake(0, 0, LYScreenWidth(), kLYScreenHeight() - kNavigationBarAndStatusBarHeight - 44 - LYSafeAreaBottom())];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:self.bottomBtn];
    [self.bottomBtn setTitle:@"新建地址" forState:UIControlStateNormal];
    [self.bottomBtn addTarget:self action:@selector(bottomBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - Event
- (void)bottomBtnClick:(UIButton *)sender {
    SEGEditAdressViewController* addNewAddress = [[SEGEditAdressViewController alloc] init];
    addNewAddress.editDelegate = self;
    addNewAddress.hidesBottomBarWhenPushed = YES;
    if (self.showType == AdressListViewControllerType_My) {
        addNewAddress.showType = EditAdressShowType_ADD;
    } else {
        addNewAddress.showType = EditAdressShowType_ADD_Order;
    }
    if (self.shouldShowConfirmView) {
        addNewAddress.shouldGoBackAddressList = YES;
    }
    [self.navigationController pushViewController:addNewAddress animated:YES];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.viewModel.myManager.seg_segaddressmodel.count;
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    SEGEditAdressViewCell* cell = [tableView dequeueReusableCellWithIdentifier:SEGEditAdressViewCellIndentifier];
    if (cell == nil) {
        cell = [[SEGEditAdressViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SEGEditAdressViewCellIndentifier];
    }
    cell.indexPath = indexPath;
    cell.adressDelegate = self;
    if (indexPath.section < self.viewModel.myManager.seg_segaddressmodel.count) {
        SEGAddressModel *data = self.viewModel.myManager.seg_segaddressmodel[indexPath.section];
        if (self.showType == AdressListViewControllerType_My) { //我的 - 配送地址
            cell.showType = SEGEditAdressViewCellShowType_NO;
            [cell.ContentBtn setSelected:[data.defaultType isEqualToString:@"1"] ? YES : NO];
            [cell.ContentLabel setTextColor:kColor_1];
            [cell.ContentLabel1 setTextColor:kColor_1];
        } else { //  订单 - 配送地址
             if (self.shouldShowConfirmView) {
                 if ([data.defaultType isEqualToString:@"1"]) { //是默认、选中
                     cell.showType = SEGEditAdressViewCellShowType_Order_SelectedNomal;
                     [cell.ContentBtn setSelected:YES];
                     [cell.ContentLabel setTextColor:kColor_T];
                     [cell.ContentLabel1 setTextColor:kColor_T];
                 } else { //没默认、没选中
                     cell.showType = SEGEditAdressViewCellShowType_Order_No;
                     [cell.ContentLabel setTextColor:kColor_1];
                     [cell.ContentLabel1 setTextColor:kColor_1];
                 }
             } else {
                 if ([data.defaultType isEqualToString:@"1"] && [data.id isEqualToString:self.addressSelected]) { //是默认、选中
                     cell.showType = SEGEditAdressViewCellShowType_Order_SelectedNomal;
                     [cell.ContentBtn setSelected:YES];
                     [cell.ContentLabel setTextColor:kColor_T];
                     [cell.ContentLabel1 setTextColor:kColor_T];
                 } else if ([data.defaultType isEqualToString:@"1"] && ![data.id isEqualToString:self.addressSelected]) { //是默认、没选中
                     cell.showType = SEGEditAdressViewCellShowType_Order_Normal;
                     [cell.ContentLabel setTextColor:kColor_1];
                     [cell.ContentLabel1 setTextColor:kColor_1];
                 } else if ([data.defaultType isEqualToString:@"0"] && [data.id isEqualToString:self.addressSelected]) { //没默认、选中
                     cell.showType = SEGEditAdressViewCellShowType_Order_Selected;
                     [cell.ContentBtn setSelected:YES];
                     [cell.ContentLabel setTextColor:kColor_T];
                     [cell.ContentLabel1 setTextColor:kColor_T];
                 } else { //没默认、没选中
                     cell.showType = SEGEditAdressViewCellShowType_Order_No;
                     [cell.ContentLabel setTextColor:kColor_1];
                     [cell.ContentLabel1 setTextColor:kColor_1];
                 }
             }
        }
        
        if (data.contactName.length > 4) { // 限制最多显示四个字
            cell.ContentLabel.text = [NSString stringWithFormat:@"%@...",[data.contactName substringToIndex:4]];
        } else {
            cell.ContentLabel.text = data.contactName;
        }
        cell.ContentLabel1.text = data.contactPhone;
        cell.ContentLabel2.text = data.userAddress;
    }
    self.indexPath = indexPath;
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
        [cell layoutIfNeeded];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.showType == AdressListViewControllerType_My) return;
    SEGAddressModel *data = self.viewModel.myManager.seg_segaddressmodel[indexPath.section];
    if (self.shouldShowConfirmView) {
        self.viewModel.currentAddress = data;
        SEGPersonalConfirmAlertView *alertView = [[SEGPersonalConfirmAlertView alloc] init];
        [alertView showAlertWithType:SEGPersonalConfirmAlertViewType_Address contentText:data.userAddress delegate:self];
    } else {
        if (self.delegate && [self.delegate respondsToSelector:@selector(responseAddressWidhData:)]) {
            [self.delegate responseAddressWidhData:data];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

#pragma mark - SEGEditAdressViewCellDelegate
// 编辑配送地址
- (void)adress_setEditAddressClick:(UIButton *)sender IndexPath:(NSIndexPath *)indexPath {
    SEGAddressModel *data = self.viewModel.myManager.seg_segaddressmodel[indexPath.section];
    SEGEditAdressViewController *addNewAddress = [[SEGEditAdressViewController alloc] init];
    addNewAddress.hidesBottomBarWhenPushed = YES;
    addNewAddress.editDelegate = self;
    addNewAddress.address = data;
    if (self.showType == AdressListViewControllerType_My) { //我的 - 配送地址
        addNewAddress.showType = EditAdressShowType_EDITE;
    } else {
        addNewAddress.showType = EditAdressShowType_EDITE_Order;
    }
    if (self.shouldShowConfirmView) {
        addNewAddress.shouldGoBackAddressList = YES;
    }
    [self.navigationController pushViewController:addNewAddress animated:YES];
}
// 删除配送地址
- (void)adress_setDeleteAddressClick:(UIButton *)sender IndexPath:(NSIndexPath *)indexPath {
    SEGAddressModel *data = self.viewModel.myManager.seg_segaddressmodel[indexPath.section];
    @weakify(self);
    [[self.viewModel.deleteAddressCommand execute:data.id] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self seg_loadData];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 设置默认地址
- (void)adress_setNormalAddressClick:(UIButton *)sender IndexPath:(NSIndexPath *)indexPath {
    for (int i = 0; i < self.viewModel.myManager.seg_segaddressmodel.count; i++) {
        SEGEditAdressViewCell* cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i]];
        if (i == indexPath.section) {
            [cell.ContentBtn setSelected:YES];
        }
        else {
            [cell.ContentBtn setSelected:NO];
        }
    }

    if (indexPath.section < self.viewModel.myManager.seg_segaddressmodel.count) {
        SEGAddressModel *data = self.viewModel.myManager.seg_segaddressmodel[indexPath.section];
        [[self.viewModel.normalAddressCommand execute:data.id] subscribeError:^(NSError * _Nullable error) {
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        }];
    }
}
- (void)responseEditAdressWidhData:(SEGAddressModel *)data {
    [self.delegate responseAddressWidhData:data];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - SEGPersonalConfirmAlertViewDelegate
- (void)alertViewConfirmButtonAction {
    // 提交地址
    [self.viewModel.updateAddressCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    @weakify(self);
    [[self.viewModel.updateAddressCommand execute:self.winnerId] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:@"提交成功"];
        if (self.delegate && [self.delegate respondsToSelector:@selector(responseAddressWidhData:)]) {
            [self.delegate responseAddressWidhData:self.viewModel.currentAddress];
        }
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - Getter
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}
- (UIButton *)bottomBtn {
    if (!_bottomBtn) {
        _bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_bottomBtn setFrame:CGRectMake(-0.5, CGRectGetHeight(self.view.bounds) - 44 - kNavigationBarAndStatusBarHeight + 0.5 - LYSafeAreaBottom(), LYScreenWidth() + 1, 44 + LYSafeAreaBottom())];
        _bottomBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, LYSafeAreaBottom(), 0);//适配iPhoneX 按钮 字向上偏移安全区域底部的距离
        [_bottomBtn setBackgroundColor:kColor_T];
        _bottomBtn.layer.borderWidth = 0.5;
        _bottomBtn.layer.borderColor = kColor_L2.CGColor;
        [_bottomBtn setTitleColor:kColor_W forState:UIControlStateNormal];
        [_bottomBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    }
    return _bottomBtn;
}
- (SEGAdressListViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGAdressListViewModel new];
    return _viewModel;
}

@end
